﻿app.service("signalrHub", ["$rootScope", "$q", function ($rootScope, $q) {
    this.init = function (hubName) {
        var self = this;
        var url = location.protocol + "//" + location.hostname + ":805/signalr/";

        self.connection = $.hubConnection(url);
        self.proxy = self.connection.createHubProxy(hubName);

        return {
            on: function(eventName, callback) {
                self.proxy.on(eventName, callback);
            },
            invoke: function (methodName) {
                return self.proxy.invoke(methodName);
            },
            start: function () {
                self.connection.stateChanged(function (state) {
                    $rootScope.$apply(function() {
                        $rootScope.$broadcast("signalr.statechanged", state);
                    });
                });

                return $q.when(self.connection.start());
            }
        };
    }
}]);